package main

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql" // 表示导入该包 但不使用，驱动包注册到了 database/sql
	"log"
	"math/rand"
	"strconv"
)

func main() {

	test2()

}

type test1 struct {
	salt string
}

func test2() {
	var structest test1
	a1 := rand.Int31()
	fmt.Println(a1)
	structest.salt = strconv.Itoa(int(a1))
	fmt.Println(structest.salt)
}

func CreateTables(db *sql.DB) {
	query := `CREATE TABLE IF NOT EXISTS testsql (
    	id INT AUTO_INCREMENT PRIMARY KEY,
		name VARCHAR(100),
		age INT
	);`

	_, err := db.Exec(query)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println("Create tables Success!")
}

func InsertSql(db *sql.DB, name string, age uint) {
	query := `INSERT INTO testsql (name, age) VALUES (?, ?)`
	_, err := db.Exec(query, name, age)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Insert Success!")
}

func ReadSql(db *sql.DB) {
	query := `SELECT * FROM testsql where name = "myc"`
	rows, err := db.Query(query)
	if err != nil {
		log.Fatal(err)
	}
	defer rows.Close()
	for rows.Next() {
		var id int
		var age []uint8
		var name string
		err := rows.Scan(&id, &age, &name)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("id:%d age:%+v name:%s\n", id, age, name)
	}
}

func DeleteSql(db *sql.DB, id int, name string) {
	query := `DELETE FROM user_basic WHERE id = ? AND name = ?`
	_, err := db.Exec(query, id, name)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Delete Success!")
}

func UpdateSql(db *sql.DB, name string, age uint, oldName string) {
	query := `UPDATE testsql SET name = ?, age = ? WHERE name = ?`
	_, err := db.Exec(query, name, age, oldName)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Update Success!")
}

func DROPTables(db *sql.DB) {
	query := `DROP TABLE IF EXISTS users;`
	_, err := db.Exec(query)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("DROP tables Success!")
}
